#include "virtualdevice.h"
#include "virtualdeviceconfig.h"
#include <libxml++/libxml++.h>
using namespace xvd;
using namespace xmlpp;

const std::string VirtualDevice::SERVER("SERVER");

VirtualDevice::VirtualDevice(const std::string& name, const std::string& devicetype, const std::string& version, const std::string& configuration) :
    m_name(name), m_devicetype(devicetype), m_language("C++"), m_version(version), m_configuration(configuration)
{
    VirtualDeviceConfig::GetInstance()->ValidateDevice(this);
    VirtualDevice::LoadConfiguration(this, m_configuration);
}

const std::string& VirtualDevice::Name() const
{
    return m_name;
}

const std::string& VirtualDevice::DeviceType() const
{
    return m_devicetype;
}

const std::string& VirtualDevice::Language() const
{
    return m_language;
}

const std::string& VirtualDevice::Version() const
{
    return m_version;
}

const std::string& VirtualDevice::Configuration() const
{
    return m_configuration;
}

bool VirtualDevice::GetPropertyByName(const std::string& propertyName, VirtualDeviceProperty& property)
{
    if (m_properties.find(propertyName) == m_properties.end()) return false;
    property = m_properties[propertyName];
    return true;
}

bool VirtualDevice::GetMethodByName(const std::string& methodName, VirtualDeviceMethod& method)
{
    if (m_methods.find(methodName) == m_methods.end()) return false;
    method = m_methods[methodName];
    return true;
}

void VirtualDevice::Start()
{

}

void VirtualDevice::Stop()
{

}

void VirtualDevice::LoadConfiguration(VirtualDevice* devicePtr, const std::string& configurationfile)
{
    try
    {
        DomParser parser;
        parser.parse_file(configurationfile);
        Node * rootnode = parser.get_document()->get_root_node();

        NodeSet imports = rootnode->find("imports/import");
        for(NodeSet::iterator it = imports.begin(); it != imports.end(); ++it)
        {
            Element *element = dynamic_cast<Element*>(*it);
            LoadConfiguration(devicePtr, element->get_attribute("file")->get_value());
        }

        NodeSet properties = rootnode->find("properties/property");
        for(NodeSet::iterator it = properties.begin(); it != properties.end(); ++it)
        {
            VirtualDeviceProperty property(*it);
            //devicePtr->m_properties[property.name()] = property;
        }
    }
    catch (const std::exception& ex)
    {
        throw;
    }
}
